package org.tinygroup.bizframe2.springboot.listener;

import org.springframework.beans.BeansException;
import org.springframework.boot.context.event.ApplicationFailedEvent;
import org.springframework.boot.context.event.ApplicationPreparedEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.core.Ordered;
import org.tinygroup.beancontainer.BeanContainerFactory;
import org.tinygroup.springutil.SpringBootBeanContainer;
import org.tinygroup.tinystarter.Starter;

public class TinyApplicationListener implements ApplicationListener<ApplicationEvent>,Ordered,ApplicationContextAware {
	
	private int order = HIGHEST_PRECEDENCE;
	
	

	private ApplicationContext applicationContext;
	
	@Override
	public void onApplicationEvent(ApplicationEvent event) {
		if (event instanceof ApplicationPreparedEvent) {
			BeanContainerFactory.initBeanContainer(SpringBootBeanContainer.class
					.getName());
			SpringBootBeanContainer beanContainer = (SpringBootBeanContainer) BeanContainerFactory
					.getBeanContainer(getClass().getClassLoader());
			beanContainer.setApplicationContext(applicationContext);
			Starter.getInstance().start(null);
		}
		if (event instanceof ContextClosedEvent
				|| event instanceof ApplicationFailedEvent) {
			Starter.getInstance().stop();
		}
	}
	
	@Override
	public int getOrder() {
		return this.order;
	}

	/**
	 * Set the order of the listener.
	 * @param order the order of the listener
	 */
	public void setOrder(int order) {
		this.order = order;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext=applicationContext;
	}
}
